package end.util.jedis;

import java.util.Set;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * ShiroRedisManager.java 2016-7-12 Copyright zhaocj Inc. All rights reserved.
 * Love Me Like Love Justin Bieber
 */
public class ShiroRedisWorker {
	// shiro cache placed database4
	// 0 代表永不过期
	private int expire = 1000 * 60 * 60;

	public int getExpire() {
		return expire;
	}

	public void setExpire(int expire) {
		this.expire = expire;
	}

	private static JedisPool jedisPool = JedisPoolUtils.getJedisPool();

	public ShiroRedisWorker() {
		super();
	}

	public byte[] get(byte[] key) {
		byte[] value = null;
		Jedis jedis = jedisPool.getResource();
		jedis.select(4);
		try {
			value = jedis.get(key);
		} finally {
			jedisPool.returnResource(jedis);
		}
		return value;
	}

	public byte[] set(byte[] key, byte[] value) {
		Jedis jedis = jedisPool.getResource();
		jedis.select(4);
		try {
			jedis.set(key, value);
			if (this.expire != 0) {
				jedis.expire(key, this.expire);
			}
		} finally {
			jedisPool.returnResource(jedis);
		}
		return value;
	}

	public byte[] set(byte[] key, byte[] value, int expire) {
		Jedis jedis = jedisPool.getResource();
		jedis.select(4);
		try {
			jedis.set(key, value);
			if (expire != 0) {
				jedis.expire(key, expire);
			}
		} finally {
			jedisPool.returnResource(jedis);
		}
		return value;
	}

	public void del(byte[] key) {
		Jedis jedis = jedisPool.getResource();
		jedis.select(4);
		try {
			jedis.del(key);
		} finally {
			jedisPool.returnResource(jedis);
		}
	}

	public void flushDB() {
		Jedis jedis = jedisPool.getResource();
		jedis.select(4);
		try {
			jedis.flushDB();
		} finally {
			jedisPool.returnResource(jedis);
		}
	}

	public Long dbSize() {
		Long dbSize = 0L;
		Jedis jedis = jedisPool.getResource();
		jedis.select(4);
		try {
			dbSize = jedis.dbSize();
		} finally {
			jedisPool.returnResource(jedis);
		}
		return dbSize;
	}

	public Set<byte[]> keys(String pattern) {
		Set<byte[]> keys = null;
		Jedis jedis = jedisPool.getResource();
		jedis.select(4);
		try {
			keys = jedis.keys(pattern.getBytes());
		} finally {
			jedisPool.returnResource(jedis);
		}
		return keys;
	}
}